package com.hc.dfs.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.hc.dfs.activity.BaseActivity;
import com.hc.dfs.activity.DocumentDetailsActivity;
import com.hc.dfs.activity.MainActivity;
import com.hc.dfs.activity.ManageActivity;
import com.hc.dfs.activity.SplashScreen;
import com.hc.dfs.entities.flow.UnsignedNode;
import com.hc.dfs.handle.DetailChengPiDan;
import com.hc.dfs.service.common.Page;
import com.hc.dfs.service.common.ParamsTable;
import com.hc.dfs.task.DoTaskMethod;
import com.hc.dfs.task.Task;

/** 
 * @author 王洪胜  E-mail:  
 * @version 创建时间：2013-3-9 上午9:52:16
 * 
 * 类说明：
 *
 */
public class MainService extends Service implements Runnable {

	//网络数据交互服务
	public com.hc.dfs.service.internet.Service service = new com.hc.dfs.service.internet.Service();
	// 保存所有的activity
    public static List<Activity> allActivities = new ArrayList<Activity>();
    // 保存前一个Activity的编号
    public static int lastAcvityId;
    // 所有任务
    public static List<Task> allTasks = new ArrayList<Task>();
    // 循环控制变量
    private boolean isrun = true;
    //执行任务的方法类
    private DoTaskMethod doTaskMethod= new DoTaskMethod();

    // 保存公文列表
    public static List<UnsignedNode> documentList = new ArrayList<UnsignedNode>();

    /**
     * 在集合里，通过name获取Activity对象
     * 
     * @param name
     * @return Activity
     */
    public static Activity getActivityByName(String name) {
        for (Activity a : allActivities) {
            if (a.getClass().getName().indexOf(name) >= 0) {
                return a;
            }
        }
        return null;
    }

    /**
     * 新建任务
     * 
     * @param task
     */
    public static void newTask(Task task) {
        // 添加一个任务
        allTasks.add(task);
    }

    /*********
     * 启动线程
     */
    @Override
    public void run() {
        while (isrun) {
            Task lastTask = null;
            if (allTasks.size() > 0) {
                //通过synchronized锁定执行doTask方法
            	synchronized (allTasks) {
                    // 获取任务
                    lastTask = allTasks.get(0);
                    // 执行任务
                    doTask(lastTask);
                }
            }
            // 如果没有任务，则等待2000ms，继续获取任务
            try {
                Thread.sleep(2000);
//                String activityName = "";
//                for(Activity a : allActivities){
//                	activityName = activityName + a.getClass().getName()+"       ";
//                }
//                System.out.println("栈内的Activity包括："+activityName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /************************
     * 很据任务ID，执行该任务
     * 
     * @param task
     */
//    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void doTask(Task task) {

        Message msg = new Message();
        System.out.println("任务编号： " + task.getTaskId());
        msg.what = task.getTaskId();
        try {
            switch (task.getTaskId()) {

            case Task.SPLASH_SCREEN://程序启动任务
            	break;
            case Task.GET_USIGNED_DOCMENT_LIST:// 获取待签公文列表
                msg.obj = doTaskMethod.getDocumentList(1);
                break;
            case Task.GET_FOLLOW_DOCUMENT_LIST:// 获取跟踪公文列表
                msg.obj = doTaskMethod.getDocumentList(2);
                break;
            case Task.GET_TODO_DOCUMENT_LIST:// 获取待办公文列表
                msg.obj = doTaskMethod.getDocumentList(3);
                break;
            case Task.GET_DOCUMENT_DETAIL://获取公文单详情
            	int docId = task.getTaskParam();
            	msg.obj=doTaskMethod.getDocumentDetail(docId);
            	break;
//            case Task.GET_FAWENGAO_DETAIL://获取发文稿详情
//            	break;
//            case Task.GET_HETONG_DETAIL://获取合同详情
//            	break;
            default:
            	break;
            }

        } catch (Exception e) {
            msg.what = -100;
            e.printStackTrace();
        }
        handler.sendMessage(msg);
        allTasks.remove(task);// 执行完任务，则移出该任务
    }

    // 当前服务的子线程Handler,负责处理更新UI操作
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(Task.Logger, "UI 更新编号：" + msg.what);
            switch (msg.what) {
            case Task.SPLASH_SCREEN:
            	break;
            case Task.GET_USIGNED_DOCMENT_LIST:
            	BaseActivity sa1 = (ManageActivity) getActivityByName("ManageActivity");
            	sa1.refresh(ManageActivity.GET_UNSIGNED_DOCUMENT_LIST_SUCCESS, msg.obj);
            	break;
            case Task.GET_FOLLOW_DOCUMENT_LIST:
            	BaseActivity sa2 = (ManageActivity) getActivityByName("ManageActivity");
            	sa2.refresh(ManageActivity.GET_FOLLOW_DOCUMENT_LIST_SUCCESS, msg.obj);
            	break;
            case Task.GET_TODO_DOCUMENT_LIST:
            	BaseActivity sa3 = (ManageActivity) getActivityByName("ManageActivity");
            	sa3.refresh(ManageActivity.GET_TODO_DOCUMENT_LIST_SUCCESS, msg.obj);
            	break;
            case Task.GET_DOCUMENT_DETAIL:
            	BaseActivity dda = (DocumentDetailsActivity) getActivityByName("DocumentDetailsActivity");
            	dda.refresh(DocumentDetailsActivity.GET_DOCUMENT_DETAIL_SUCCESS, msg.obj);
            	break;
//            case Task.GET_FAWENGAO_DETAIL:
//            	break;
//            case Task.GET_HETONG_DETAIL:
//            	break;
            case -100:
            	System.out.println("网络异常，请检查网络并重试！");
            	break;
            default:
                break;
            }
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();
        isrun = true;
        Thread thread = new Thread(this);
        thread.start();
        System.out.println("+++++++++++++++++++++++++++++++创建MainService");
        System.out.println("***************************************************服务线程id是："+thread.getId());
    }

    @Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		System.out.println("_________________________________________________________启动MainService");
	}

	@Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isrun = false;
    }

    /**************
     * 退出程序
     */
    public static void exitApp(Context context) {

        // 出栈所有Activity
        if (allActivities != null) {
            for (Activity ac : allActivities) {
                ac.finish();
            }
        }

        // 关闭服务
        Intent it = new Intent(context, MainService.class);
        context.stopService(it);
        System.exit(0);

    }
    
}
